import {onActivated, Ref, ref, reactive, UnwrapNestedRefs} from "vue"
import {HttpResultPaging, PaginationType} from "@/types/project";
import {getPaginationDefaultSize} from "@/units/system";

/**
 * 请求参数结构体
 */
export type HttpQuery = {
    page: number
    size: number
    [key: string]: any
}

/**
 * 通用分页结构体
 * @param httpFunctuon 数据获取回调
 * @param size_num 初始分页大小
 * @param auto 自动获取数据
 */
export function useHttpPagingResult<T>(httpFunctuon: (qyery?: HttpQuery) => Promise<HttpResultPaging<T>>, size_num: number = 0, auto: boolean = true) {
    /**
     * 分页数据
     */
    const pagination: UnwrapNestedRefs<PaginationType> = reactive({
        page: 1,
        size: size_num ? size_num : getPaginationDefaultSize(),
        total: 0
    })

    /**
     * 接口数据
     */
    const list: Ref<Array<T>> = ref([]);

    /**
     * 加载状态
     */
    const loading: Ref<boolean> = ref(false)


    /**
     * 执行回调获取数据
     */
    function getRequestData(query?: HttpQuery) {
        if (!loading.value) {
            loading.value = true
            const httpResult: Promise<HttpResultPaging<T>> = httpFunctuon({
                page: query?.page ? query?.page : pagination.page,
                size: query?.size ? query?.size : pagination.size
            })
            httpResult?.then(resdata => {
                if (resdata.code === 200) {
                    pagination.page = resdata.data.current
                    pagination.size = resdata.data.size
                    pagination.total = resdata.data.total
                    list.value = resdata.data.list
                }
                loading.value = false
            })
        }
    }


    /**
     * 进入页面或回到页面自动获取数据
     */
    onActivated(() => {
        if (auto) {
            getRequestData({page: pagination.page, size: pagination.size})
        }
    })


    /**
     * 暴露属性和方法
     */
    return {
        getRequestData,
        list,
        pagination,
        loading
    }
}